package com.caigou.service.impl;

import com.caigou.bean.cms.entity.AdConfig;
import com.caigou.bean.cms.entity.AdList;
import com.caigou.bean.cms.entity.AdOperationLog;
import com.caigou.bean.cms.param.AdConfigParam;
import com.caigou.bean.cms.param.AdListParam;
import com.caigou.bean.exam.entity.Users;
import com.caigou.component.HtmlBuildAdComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.AdConfigMapper;
import com.caigou.pojo.*;
import com.caigou.service.*;
import com.caigou.util.DateUtil;
import com.caigou.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("adConfigService")
public class AdConfigServiceImpl implements AdConfigService {

    @Resource
    private AdConfigMapper adConfigMapper;
    @Resource
    private AdListService adListService;
    @Resource
    private AdOperationLogService adOperationLogService;
    @Resource
    private IUserBaseInfoService userBaseInfoService;// 用户信息获取
    @Resource
    private AdContractService adContractService;

    @Resource
    private HtmlBuildAdComponent htmlBuildAdComponent;

    @Override
    public Result loadAdConfigList(AdConfigParam param) {
        List<AdConfigList> advertisingPositionList = adConfigMapper.loadAdConfigList(param);
        return Result.success(advertisingPositionList);
    }

    @Override
    public Result loadAdConfigExportList(AdConfigParam param) {
        List<AdvertExportList> list = adConfigMapper.loadAdConfigExportList(param);
        return Result.success(list);
    }

    @Override
    public Result updateAdConfigAdType(AdConfigParam param, Users users) {
        if (null != param.getAdConfigList()){
            param.getAdConfigList().forEach(item -> {
                AdConfig adConfig = adConfigMapper.loadAdConfigByAdId(item);
                AdList adList = adListService.loadAdListByConfig(item);
                if (null != adList && adList.getAdType() == 2){
                    // 强制关闭当前广告
                    adListService.updateAdListStatus(adList.getId(), -1);
                    // 设置当前广告位所在默认广告的使用状态
                    adListService.updateAdListToDefault(item,1);
                    // 保存操作记录
                    AdOperationLog adOperationLog = new AdOperationLog();
                    adOperationLog.setModuleType(1);
                    adOperationLog.setActionType("手工更换默认广告");
                    adOperationLog.setUserId(users.getUserid());
                    adOperationLog.setAdConfigId(item);
                    adOperationLog.setAdContractCode("");
                    adOperationLog.setAdContractId(0);
                    adOperationLogService.saveOperationData(adOperationLog);
                }
                // 更新当前广告位碎片
                htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
            });
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result loadAdConfigInfo(AdConfigParam param) {
        AdConfigInfo adConfigInfo = adConfigMapper.loadAdConfigInfo(param.getConfigId());
        if (null != adConfigInfo){
            // 获取当前广告位下的广告列表(非下架状态)
            List<AdConfigInfoAdList> adList = adListService.loadAdConfigInfoAdList(param.getConfigId());
            adConfigInfo.setAdList(adList);
        }
        return Result.success(adConfigInfo);
    }

    @Override
    public Result saveAdList(AdConfigParam param, Users users) {
        // 合同是否存在判定
        if (adContractService.loadAdContractExit(param.getContractId()) == 0) return Result.error(ResponseEnum.CONTRACT_NOT_FONT);
        // 判定填写的时间段是否正常
        int timeResult = adListService.loadTimeQuantum(param.getConfigId(),param.getStartTime(),param.getEndTime(),null);
        if (timeResult > 0) return Result.error(ResponseEnum.TIME_QUANTUM_ERROR);
        // 判定当前选择的合同在当前广告位是否已经被使用
        int contractResult = adListService.loadContractQuantum(param.getConfigId(),param.getContractId());
        if (contractResult > 0) return Result.error(ResponseEnum.CONTRACT_QUANTUM_ERROR);
        // 时间参数判定
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowData = format.format(new Date());
        long startTime = DateUtil.stringtoDate(param.getStartTime(),"yyyy-MM-dd").getTime();
        long endTime = DateUtil.stringtoDate(param.getEndTime(),"yyyy-MM-dd").getTime();
        long nowTime = DateUtil.stringtoDate(nowData,"yyyy-MM-dd").getTime();
        if (startTime < nowTime || endTime < nowTime || startTime == endTime) return Result.error(ResponseEnum.AD_LIST_TIME_ERROR);
        // 保存广告位数据（今天大于等于开始时间则设置状态为1）
        int status = 0;
        if (startTime == nowTime){// 开始时间选择的今天的话，则设置为当前广告位的状态为1
            status = 1;
            // 设置当前广告位的广告位下架状态
            AdList adList = adListService.loadDefaultAdList(param.getConfigId());
            adListService.updateAdListStatus(adList.getId(), 0);
        }
        log.info("计算的status结果是----->"+status);
        adListService.saveAdList(param.getConfigId(),param.getContractId(),param.getJumpUrl(),param.getImgId(),param.getImgUrl(),param.getStartTime(),param.getEndTime(),status);
        AdConfig adConfig = adConfigMapper.loadAdConfigByAdId(param.getConfigId());
        if (status == 1){
            // 更新当前静态页
            htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
        }
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(1);
        current.setActionType("增加预设广告");
        current.setUserId(users.getUserid());
        current.setAdConfigId(param.getConfigId());
        current.setAdContractCode("");
        current.setAdContractId(0);
        adOperationLogService.saveOperationData(current);
        // 如果同步广告位有数据，则进行同步新增
        if (null != param.getSyncData() && param.getSyncData().size() > 0){
            List<String> result = new ArrayList<>();
            // 进行广告位新增的数据同步根据同步的刊例编号查询广告位ID
            int maxSize = param.getSyncData().size();
            int errCount = 0;
            for (Integer item: param.getSyncData()){
                AdConfigInfo config = adConfigMapper.loadAdConfigInfo(item);
                int syncTimeResult = adListService.loadTimeQuantum(item,param.getStartTime(),param.getEndTime(),null);
                if (syncTimeResult == 0){
                    int syncContractResult = adListService.loadContractQuantum(item,param.getContractId());
                    if (syncContractResult == 0){
                        if (status == 1){
                            log.info("同步的数据需要上架");
                            AdList adList = adListService.loadDefaultAdList(item);
                            log.info("更新ID值---->为下架状态"+adList.getId());
                            adListService.updateAdListStatus(adList.getId(), 0);
                        }
                        adListService.saveAdList(item,param.getContractId(),param.getJumpUrl(),param.getImgId(),param.getImgUrl(),param.getStartTime(),param.getEndTime(),status);
                        if (status == 1){
                            // 更新当前静态页
                            htmlBuildAdComponent.buildAdHtml(config.getAdCode());
                        }
                        // 保存其它操作记录
                        AdOperationLog other = new AdOperationLog();
                        other.setModuleType(1);
                        other.setActionType("被"+adConfig.getAdCode()+"同步增加预设广告");
                        other.setUserId(users.getUserid());
                        other.setAdConfigId(item);
                        other.setAdContractId(0);
                        other.setAdContractCode("");
                        adOperationLogService.saveOperationData(other);
                    } else {
                        errCount = errCount + 1;
                        result.add(config.getAdCode());
                    }
                } else {
                    errCount = errCount + 1;
                    result.add(config.getAdCode());
                }
            }
            return Result.success("共同步"+maxSize+"个广告，其中"+errCount+"个不成功！"+result.toString());
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result loadAdListInfo(AdConfigParam param) {
        AdListInfo adListInfo = adListService.loadAdListInfo(param.getAdListId());
        return Result.success(adListInfo);
    }

    @Override
    public Result updateAdListInfo(AdConfigParam param, Users users) {
        AdList adList = adListService.loadAdListById(param.getAdListId());
        AdConfigInfo adConfig = adConfigMapper.loadAdConfigInfo(param.getConfigId());
        if (null == adList) return Result.error(ResponseEnum.AD_LIST_ERROR);
        if (adList.getAdType() == 1){
            // 默认广告--只进行改图操作
            adListService.updateAdListInfo(param.getAdListId(),null,null,param.getJumpUrl(),param.getImgId(),param.getImgUrl(),adList.getAdStatus());
            // 更新当前广告位静态页
            htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
            // 保存当前操作记录
            AdOperationLog current = new AdOperationLog();
            current.setModuleType(1);
            current.setActionType("编辑默认广告");
            current.setUserId(users.getUserid());
            current.setAdConfigId(param.getConfigId());
            current.setAdContractId(0);
            current.setAdContractCode("");
            adOperationLogService.saveOperationData(current);

            // 如果同步广告位有数据，则进行同步新增
            if (null != param.getSyncData() && param.getSyncData().size() > 0){
                List<String> result = new ArrayList<>();
                // 进行广告位新增的数据同步根据同步的刊例编号查询广告位ID
                int maxSize = param.getSyncData().size();
                int errCount = 0;
                for (Integer item: param.getSyncData()){
                    AdConfigInfo config = adConfigMapper.loadAdConfigInfo(item);
                    // 获取当前广告位是否有相同合同的广告
                    AdList sameAdList = adListService.loadDefaultAdList(config.getId());
                    if (null != sameAdList){
                        adListService.updateAdListInfo(sameAdList.getId(),param.getStartTime(),param.getEndTime(),param.getJumpUrl(),param.getImgId(),param.getImgUrl(),sameAdList.getAdStatus());
                        // 保存其它操作记录
                        AdOperationLog other = new AdOperationLog();
                        other.setModuleType(1);
                        other.setActionType("被"+adConfig.getAdCode()+"同步编辑默认广告");
                        other.setUserId(users.getUserid());
                        other.setAdConfigId(item);
                        other.setAdContractId(0);
                        other.setAdContractCode("");
                        adOperationLogService.saveOperationData(other);
                    } else {
                        errCount = errCount + 1;
                        result.add(config.getAdCode());
                    }
                }
                return Result.success("共同步"+maxSize+"个广告，其中"+errCount+"个不成功！"+result.toString());
            }
        } else {
            // 预设广告--判定填写的时间段是否正常
            int timeResult = adListService.loadTimeQuantum(param.getConfigId(),param.getStartTime(),param.getEndTime(),param.getAdListId());
            if (timeResult > 0) return Result.error(ResponseEnum.TIME_QUANTUM_ERROR);
            // 时间参数判定--是否即时上架
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String nowData = format.format(new Date());
            long startTime = DateUtil.stringtoDate(param.getStartTime(),"yyyy-MM-dd").getTime();
            long endTime = DateUtil.stringtoDate(param.getEndTime(),"yyyy-MM-dd").getTime();
            long nowTime = DateUtil.stringtoDate(nowData,"yyyy-MM-dd").getTime();
            if (startTime < nowTime || endTime < nowTime || startTime == endTime) return Result.error(ResponseEnum.AD_LIST_TIME_ERROR);
            // 保存广告位数据（今天大于等于开始时间则设置状态为1）
            int status = 0;
            if (startTime == nowTime){// 开始时间选择的今天的话，则设置为当前广告位的状态为1
                status = 1;
                // 设置当前广告位的广告位下架状态
                AdList useAdList = adListService.loadDefaultAdList(param.getConfigId());
                adListService.updateAdListStatus(useAdList.getId(), 0);
            }
            // 进行数据修改
            adListService.updateAdListInfo(param.getAdListId(),param.getStartTime(),param.getEndTime(),param.getJumpUrl(),param.getImgId(),param.getImgUrl(),status);
            // 判定如果当前广告位没有正在使用的广告--设置为默认广告的使用状态
            int publicCount = adListService.loadPublicCountByConfig(param.getConfigId());
            if (publicCount == 0){
                // 把当前广告位设置为默认广告
                adListService.updateAdListToDefault(param.getConfigId(),1);
            }
            // 更新当前广告位静态页
            htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
            // 保存当前操作记录
            AdOperationLog current = new AdOperationLog();
            current.setModuleType(1);
            current.setActionType("编辑预设广告");
            current.setUserId(users.getUserid());
            current.setAdConfigId(param.getConfigId());
            current.setAdContractId(0);
            current.setAdContractCode("");
            adOperationLogService.saveOperationData(current);
            // 如果同步广告位有数据，则进行同步新增
            if (null != param.getSyncData() && param.getSyncData().size() > 0){
                List<String> result = new ArrayList<>();
                // 进行广告位新增的数据同步根据同步的刊例编号查询广告位ID
                int maxSize = param.getSyncData().size();
                int errCount = 0;
                for (Integer item: param.getSyncData()){
                    AdConfigInfo config = adConfigMapper.loadAdConfigInfo(item);
                    // 获取当前广告位是否有相同合同的广告
                    AdList sameAdList = adListService.loadAdListByConfigAndContract(item,param.getContractId());
                    if (null != sameAdList){
                        // 进行同步数据的保存
                        if (status == 1){
                            AdList adList1 = adListService.loadDefaultAdList(item);
                            adListService.updateAdListStatus(adList1.getId(), 0);
                        }
                        adListService.updateAdListInfo(sameAdList.getId(),param.getStartTime(),param.getEndTime(),param.getJumpUrl(),param.getImgId(),param.getImgUrl(),status);
                        // 判定如果当前广告位没有正在使用的广告--设置为默认广告的使用状态
                        int count = adListService.loadPublicCountByConfig(config.getId());
                        if (count == 0){
                            // 把当前广告位设置为默认广告
                            adListService.updateAdListToDefault(config.getId(),1);
                        }
                        if (status == 1){
                            // 更新当前静态页
                            htmlBuildAdComponent.buildAdHtml(config.getAdCode());
                        }
                        // 保存其它操作记录
                        AdOperationLog other = new AdOperationLog();
                        other.setModuleType(1);
                        other.setActionType("被"+adConfig.getAdCode()+"同步编辑预设广告");
                        other.setUserId(users.getUserid());
                        other.setAdConfigId(item);
                        other.setAdContractId(0);
                        other.setAdContractCode("");
                        adOperationLogService.saveOperationData(other);
                    } else {
                        errCount = errCount + 1;
                        result.add(config.getAdCode());
                    }
                }
                return Result.success("共同步"+maxSize+"个广告，其中"+errCount+"个不成功！"+result.toString());
            }
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result updateAdListStatus(AdConfigParam param, Users users) {
        // 只有当广告是预设广告并且是正在引用状态，才能够进行下架操作
        AdList ad = adListService.loadAdListById(param.getAdListId());
        if (null == ad || ad.getAdType() != 2 || ad.getAdStatus() != 1) return Result.error(ResponseEnum.AD_LIST_ERROR);
        // 下架当前广告
        adListService.updateAdListStatus(param.getAdListId(), -1);
        // 替换当前广告位的默认广告状态
        adListService.updateAdListToDefault(param.getConfigId(),1);
        // 更新当前广告位
        AdConfig adConfig = adConfigMapper.loadAdConfigByAdId(param.getConfigId());
        htmlBuildAdComponent.buildAdHtml(adConfig.getAdCode());
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(1);
        current.setActionType("手动下架预设广告");
        current.setUserId(users.getUserid());
        current.setAdConfigId(param.getConfigId());
        current.setAdContractId(0);
        current.setAdContractCode("");
        adOperationLogService.saveOperationData(current);
        // 进行广告同步下架
        if (null != param.getSyncData() && param.getSyncData().size() > 0){
            List<String> result = new ArrayList<>();
            int maxSize = param.getSyncData().size();
            int errCount = 0;
            for (Integer item :param.getSyncData()){
                AdConfigInfo config = adConfigMapper.loadAdConfigInfo(item);
                AdList adList = adListService.loadAdListByConfigAndContract(item,param.getContractId());
                if (null != adList && adList.getAdType() == 2 && adList.getAdStatus() == 1){
                    // 下架当前广告
                    adListService.updateAdListStatus(adList.getId(), -1);
                    // 替换当前广告位的默认广告状态
                    adListService.updateAdListToDefault(item,1);
                    // 保存其它操作记录
                    AdOperationLog other = new AdOperationLog();
                    other.setModuleType(1);
                    other.setActionType("被"+adConfig.getAdCode()+"同步下架预设广告");
                    other.setUserId(users.getUserid());
                    other.setAdConfigId(item);
                    other.setAdContractId(0);
                    other.setAdContractCode("");
                    adOperationLogService.saveOperationData(other);
                    // 更新当前广告位
                    htmlBuildAdComponent.buildAdHtml(config.getAdCode());
                } else {
                    errCount = errCount + 1;
                    result.add(config.getAdCode());
                }
            }
            return Result.success("共同步"+maxSize+"个广告，其中"+errCount+"个不成功！"+result.toString());
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result deleteAdList(AdConfigParam param, Users users) {
        // 只有在排队的预设广告可以进行删除
        AdList ad = adListService.loadAdListById(param.getAdListId());
        if (null == ad || ad.getAdType() != 2 || ad.getAdStatus() != 0) return Result.error(ResponseEnum.AD_LIST_DELETE_ERROR);
        AdConfig adConfig = adConfigMapper.loadAdConfigByAdList(param.getAdListId());
        // 删除预设广告
        adListService.deleteAdList(param.getAdListId());
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(1);
        current.setActionType("删除预设广告");
        current.setUserId(users.getUserid());
        current.setAdConfigId(param.getConfigId());
        current.setAdContractId(0);
        current.setAdContractCode("");
        adOperationLogService.saveOperationData(current);
        if (null != param.getSyncData() && param.getSyncData().size() > 0){
            List<String> result = new ArrayList<>();
            int maxSize = param.getSyncData().size();
            int errCount = 0;
            for (Integer item : param.getSyncData()){
                AdConfigInfo config = adConfigMapper.loadAdConfigInfo(item);
                AdList adList = adListService.loadAdListByConfigAndContract(item,param.getContractId());
                if (null != adList && adList.getAdType() == 2 && adList.getAdStatus() == 0){
                    adListService.deleteAdList(adList.getId());
                    // 保存其它操作记录
                    AdOperationLog other = new AdOperationLog();
                    other.setModuleType(1);
                    other.setActionType("被"+adConfig.getAdCode()+"同步删除预设广告");
                    other.setUserId(users.getUserid());
                    other.setAdConfigId(item);
                    other.setAdContractId(0);
                    other.setAdContractCode("");
                    adOperationLogService.saveOperationData(other);
                } else {
                    errCount = errCount + 1;
                    result.add(config.getAdCode());
                }
            }
            return Result.success("共同步"+maxSize+"个广告，其中"+errCount+"个不成功！"+result.toString());
        }
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result updateAdConfigStatus(AdConfigParam param, Users users) {
        adConfigMapper.updateAdConfigStatus(param.getConfigId(),param.getAdShowStatus(),param.getAdLogoStatus());
        // 保存当前操作记录
        String actionType01 = "";
        if (param.getAdShowStatus() == 1){
            actionType01 = "开启广告位";
        } else {
            actionType01 = "关闭广告位";
        }
        String actionType02 = "";
        if (param.getAdLogoStatus() == 1){
            actionType02 = "开启广告logo";
        } else {
            actionType02 = "关闭广告logo";
        }
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(1);
        current.setActionType(actionType01 + "或" + actionType02);
        current.setUserId(users.getUserid());
        current.setAdConfigId(param.getConfigId());
        current.setAdContractId(0);
        current.setAdContractCode("");
        adOperationLogService.saveOperationData(current);

        // 更新当前广告位
        htmlBuildAdComponent.buildAdHtml(adConfigMapper.loadAdConfigByAdId(param.getConfigId()).getAdCode());
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result loadOperationList(AdConfigParam param) {
        if (param.getSearchType() == 1){
            // 查询的操作人根据昵称获取用户ID
            param.setTitle(userBaseInfoService.loadUserIdByName(param.getTitle()));
        }
        PageHelper.startPage(param.getPage(), param.getSize());
        List<OperationList> operationList = adOperationLogService.loadOperationList(param);
        if (null != operationList){
            operationList.forEach(item -> item.setUserId(userBaseInfoService.loadUserName(item.getUserId())));
        }
        PageInfo<OperationList> list = new PageInfo<>(operationList);
        return Result.success(list);
    }

    @Override
    public AdConfig loadAdConfigByAdCode(String adConfigCode) {
        return adConfigMapper.loadAdConfigByAdCode(adConfigCode);
    }

    @Override
    public AdConfig loadAdConfigByAdId(Integer adConfigId) {
        return adConfigMapper.loadAdConfigByAdId(adConfigId);
    }

    @Override
    public List<AdConfig> loadAdConfigListByContractRelease(Integer adContractId) {
        return adConfigMapper.loadAdConfigListByContractRelease(adContractId);
    }

    @Override
    public List<AdConfigList> loadSyncAdConfigList(Integer adConfigId, String title, Integer sortType) {
        AdConfig adConfig = adConfigMapper.loadAdConfigByAdId(adConfigId);
        return adConfigMapper.loadSyncAdConfigList(adConfig.getAdCode(),adConfig.getAdSync(),title,sortType);
    }

    @Override
    public AdConfig loadAdConfigByAdList(Integer adListId) {
        return adConfigMapper.loadAdConfigByAdList(adListId);
    }

    @Override
    public List<AdListMobile> loadMobileListAdData() {
        return adConfigMapper.loadMobileListAdData();
    }

    @Override
    public List<AdListMobile> loadMobileAdData() {
        return adConfigMapper.loadMobileAdData();
    }
}
